package com.andox.fn.inf.rpc.rest.filter;

import com.andox.fn.inf.rpc.rest.RpcRequest;
import com.andox.fn.inf.rpc.rest.RpcResponse;
import com.andox.fn.inf.rpc.rest.ResponseCodes;
import com.andox.fn.inf.rpc.rest.common.Constants;

/**
 * server 
 * @author zhangqi
 *
 */
public class TimeoutFilter implements Filter{

	@Override
	public RpcResponse invoke(Invoker nextInvoker, RpcRequest request) {
		long start = System.currentTimeMillis();
		RpcResponse res = nextInvoker.invoke(request);
		Integer timeout = nextInvoker.getConfig().getConfigOfMethod(request.getMethod(), "timeout", Constants.DEFAULT_TIMEOUT_IN_MILLISECONDS);
		if (System.currentTimeMillis() - start > timeout) {
			String em = String.format("server timeout in %s ms", timeout);
			return RpcResponse.failed(request.getOpaque(), ResponseCodes.TIMEOUT_ERROR, em);
		}
		
		return res;
	}
}